import json
import random

import httpx
from django.http import HttpResponse, JsonResponse

from .models import ForwardConfig


def forward(request):
    namespace = request.headers.get('Namespaceid')
    service_name = request.headers.get('Servicename')
    if not namespace:
        namespace = request.GET.get('namespaceId')
    if not service_name:
        service_name = request.GET.get('serviceName')
    forward_config = ForwardConfig.objects.filter(namespace=namespace, service_name=service_name).first()
    if not forward_config:
        return JsonResponse(status=404, data={"status": False, "code": 10404, 'error_message': 'service not found'})
    hosts = json.loads(forward_config.hosts)
    if not hosts:
        return JsonResponse(status=404, data={"status": False, "code": 10405, 'error_message': 'service not found'})
    host = random.choices(hosts, weights=[host.get('weight') for host in hosts])[0]
    # hosts.remove(host)
    headers = dict([[key, value] for key, value in request.headers.items()])
    with httpx.Client() as client:
        resp = client.request(method=str.upper(request.method), headers=headers, cookies=request.COOKIES,
            url=f'http://{host.get("ip")}:{host.get("port")}{request.path}',
            data=request.body if request.body else request.POST.dict())
        response = HttpResponse(content=resp.content, status=resp.status_code)
        for item in resp.cookies.items():
            if isinstance(item, tuple):
                if request.COOKIES.get(item[0]) == item[1]:
                    continue
                response.set_cookie(item[0], item[1])
        response['X-Frame-Options'] = resp.headers.get('x-frame-options')
        response["Content-type"] = resp.headers.get('content-type')
        return response
